/**
 * 文件描述如下：
 * 1. 射线管理类
 * 2. 检测框线的点击
 * 3.
 * 4.
 */

import { ElMessage } from 'element-plus'
import { Raycaster, Vector2, Vector3 } from 'three'
import { mainStore } from '@/store/mainStore.js'
const store = mainStore()

export default class RaycasterManger {
  constructor(params) {
    this.scene = params.scene
    this.camera = params.camera
    this._raycaster = new Raycaster()

    window.checkRaycastToCarBox = this.checkRaycastToBox.bind(this)
  }

  // 只检测线框组
  checkRaycastToBox(event, params) {
    // 计算鼠标的归一化设备坐标
    const mouse = new Vector2()
    mouse.x = (params.x / params.w) * 2 - 1
    mouse.y = -(params.y / params.h) * 2 + 1

    // 计算物体和射线的相交情况
    this._raycaster.setFromCamera(mouse, this.camera)

    let resArr = this.scene.children.filter((item) => item.name === 'carBorderGroup')

    // 遍历场景 发出射线
    const intersects = this._raycaster.intersectObjects(resArr)

    if (intersects.length >= 1) {
      let model = intersects.find((item) => item.object.type == 'Mesh')?.object
      if (!model) model = intersects[0].object

      return model
    }

    if (intersects.length < 1) {
      ElMessage.info('未检测到物体')
      return null
    }
  }
}
